
package cz.muni.fi.pb138.accountingRecords;

import javax.xml.XMLConstants;
import javax.xml.transform.dom.DOMSource;
import javax.xml.validation.Schema;
import javax.xml.validation.SchemaFactory;
import javax.xml.validation.Validator;
import org.w3c.dom.Document;

/**
 * Class for validating XML document according to XML schema
 *
 * @author Jaroslav Klech
 */
public class XMLValidator {
    private Schema schema;
    /**
     * Contructor for XMLValidator creates XML validator
     * 
     * @param schemaPath path to xsd file in classpath
     * @throws IllegalArgumentException if can't load xsd file
     */
    public XMLValidator(String schemaPath) {
        try {
            String language = XMLConstants.W3C_XML_SCHEMA_NS_URI;
            SchemaFactory factory = SchemaFactory.newInstance(language);
            
            schema = factory.newSchema(XMLValidator.class.getResource(schemaPath));
        } catch (Exception ex) {
            throw new IllegalArgumentException("Failed to lode XML Schema file",ex);
        }
    }
    
    /**
     * Validates givem Document
     * 
     * @param doc XML document for validation
     * @throws ServiceFailureException if Document isn't valid
     */
    public void checkXML(Document doc){            
        try{
            Validator validator = schema.newValidator();
            validator.validate(new DOMSource(doc));
        }catch(Exception ex){
            throw new ServiceFailureException("XML is not valid",ex);
        }
    }
    
}
